/**
 * Created by user on 2018/4/18.
 */
var fs = require('fs')
var path = require('path')
var count = 0
var script = '<script>' +
'alert(2222);'+
'var _$ = $;' +
'var manager = {' +
    '	timer: null,' +
    '	setBottom(){' +
        '		var dom = _$("#app>div>div");' +
        '		_$("html").scrollTop = dom.clientHeight;' +
        '	},' +
        '	start() {' +
            '		this.timer && clearInterval(this.timer);' +
            '		this.timer = setInterval(this.setBottom, 2000);' +
            '	},' +
            '	stop() {' +
                '		this.timer && clearInterval(this.timer);' +
                '	}' +
                '};' +
                '</script>'
console.log(JSON.stringify({'name': 'tom'}))
console.log('path', path.join(path.resolve('../logs'), 'file_' + count + '.json'))
const needHost = [
    'm.weibo.cn',
    'passport.weibo.cn'
]
module.exports = {
    *beforeDealHttpsRequest(requestDetail) {
        return true
    },
    *beforeSendRequest(requestDetail) {
        // const localResponse = {
        //     statusCode: 200,
        //     header: { 'Content-Type': 'application/json' },
        //     body: '{"hello": "this is local response"}'
        // };
        // let accept = requestDetail.requestOptions.headers['Accept'];
        // if (accept && accept.indexOf('image') >= 0) {
        //     return {
        //         response: localResponse
        //     }
        // }
        return null
    },
    *beforeSendResponse(requestDetail, responseDetail) {
        const { url, requestOptions } = requestDetail
        const { headers } = requestOptions
        // console.log('headers', JSON.stringify(headers))
        
        var accept = headers['Accept']
        console.log('url', url, accept)
        if (accept && accept.indexOf('text/html') >= 0 && url.indexOf('https://m.weibo.cn/p/') >= 0) {
            console.log('123213213')
            var newResponse = Object.assign({}, responseDetail.response);
            newResponse.body += script;
            return { response: newResponse }
        }
        // if (requestDetail.url === 'http://httpbin.org/user-agent') {
        //     const newResponse = responseDetail.response;
        //     newResponse.body += '-- AnyProxy Hacked! --';
        //     return new Promise((resolve, reject) => {
        //         setTimeout(() => { // delay the response for 5s
        //         resolve({ response: newResponse });
        //         }, 5000);
        //     });
        // }

        return null
    }
}

function checkNeed(hostname) {
    var need = false
    var reg = new RegExp(hostname)
    for (var i in needHost) {
        if (reg.test(needHost[i])) {
            need = true
            break
        }
    }
    return need
}

function writeFile(data, _path, type) {
    var filename = path.join(path.resolve('../logs'), 'file_' + _path + '.' + type)
    console.log('1', filename)
    fs.appendFile(filename, toUnicode(data), function (err) {
        if (err) {
            console.log("文件写入失败")
        } else {
            console.log("文件追加成功");

        }
    })
}
function toUnicode(s) {
    return s.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g, function () {
        return "\\u" + RegExp["$1"].charCodeAt(0).toString(16);
    });
}
